<template>
  <div class="wrapper">
    <div class="search">
      <Form layout="inline" :model="formState" @finish="handleFinish">
        <Form.Item label="用户名称">
          <Input v-model:value="formState.username" placeholder="用户名称" allowClear>
            <template #prefix><UserOutlined style="color: rgb(0 0 0 / 25%)" /></template>
          </Input>
        </Form.Item>
        <Form.Item label="状态">
          <Select
            v-model:value="formState.active"
            style="width: 150px"
            placeholder="请选择状态"
            allowClear
            :options="[
              { label: '启用', value: '1' },
              { label: '停用', value: '0' },
            ]"
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" html-type="submit" @click="findList"> 搜索 </Button>
        </Form.Item>
        <Form.Item>
          <Button @click="reset"> 重置 </Button>
        </Form.Item>
      </Form>
    </div>
    <div class="tableWrapeer">
      <div class="btnUnion">
        <Button type="primary" @click="addUser"> 新增用户 </Button>
      </div>
      <Table :columns="columns" :data-source="dataSource" :pagination="false">
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'action'">
            <span style="display: none">{{ text }}</span>
            <span>
              <Button size="small" type="primary" @click="editUser(record.id)">
                <template #icon>
                  <EditOutlined />
                </template>
              </Button>
              &nbsp;&nbsp;
              <Popconfirm
                title="确认重置该用户的密码吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="resetPwd(record.id)"
              >
                <Button size="small" type="warning"> 重置密码 </Button>
              </Popconfirm>
              &nbsp;&nbsp;
              <Popconfirm
                title="确认删除该用户吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="delUser(record.id)"
              >
                <Button size="small" type="danger">
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                </Button>
              </Popconfirm>
            </span>
          </template>
        </template>
      </Table>
    </div>
    <!-- 新增编辑抽屉 -->
    <Drawer
      v-model:visible="visible"
      width="40%"
      class="custom-class"
      style="color: red"
      :title="drawTit"
      placement="right"
      @after-visible-change="afterVisibleChange"
    >
      <Form :model="formObj" :rules="rules" ref="formRef">
        <div class="formFlex">
          <Form.Item label="用户名称" name="username">
            <Input v-model:value="formObj.username" placeholder="用户名称" :disabled="formObj.id">
              <template #prefix><UserOutlined style="color: rgb(0 0 0 / 25%)" /></template>
            </Input>
          </Form.Item>
          <Form.Item label="用户昵称" name="nickname">
            <Input v-model:value="formObj.nickname" placeholder="用户地址">
              <template #prefix><UserOutlined style="color: rgb(0 0 0 / 25%)" /></template>
            </Input>
          </Form.Item>
        </div>
        <div class="formFlex">
          <Form.Item label="用户绑定的角色" name="role">
            <Select
              v-model:value="formObj.role"
              mode="multiple"
              style="width: 200px"
              showSearch
              placeholder="Please select"
              :options="roleData"
              @change="handleChange"
            />
          </Form.Item>
          <Form.Item label="状态">
            <Select
              v-model:value="formObj.active"
              style="width: 150px"
              placeholder="请选择状态"
              allowClear
              :options="[
                { label: '启用', value: '1' },
                { label: '停用', value: '0' },
              ]"
            />
          </Form.Item>
        </div>
        <div class="formFlex">
          <Form.Item label="用户头像" name="avatar">
            <MyUpload :imgPic="formObj.avatar" @change-cover="changeCover" />
          </Form.Item>
        </div>
        <Form.Item :wrapper-col="{ span: 14, offset: 8 }">
          <Button @click="handlerClose"> 取消 </Button>
          <Button @click="btnOk" type="primary" style="margin-left: 20px"> 确认 </Button>
        </Form.Item>
      </Form>
    </Drawer>
  </div>
</template>
<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { columns } from './user.data';
  import {
    createUser,
    deleteUser,
    updateUser,
    getUserList,
    getUserDetail,
    resetUserPwd,
  } from '/@/api/sys/user';
  import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import MyUpload from '@/components/MyUpload/index.vue';
  import md5 from 'md5';
  import { Table, Form, Input, Button, Select, Drawer, message, Popconfirm } from 'ant-design-vue';
  import { getRoleList } from '/@/api/sys/role';

  onMounted(() => {
    findList();
    getRoleSelectList();
  });

  const dataSource = ref([]);
  const drawTit = ref('新建用户');
  const formState = reactive({});
  const formObj = ref({});
  const rules = reactive({
    username: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
    nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
    role: [{ required: true, message: '请选择要绑定的角色', trigger: 'change' }],
    avatar: [{ required: true, message: '请上传用户头像', trigger: 'change' }],
  });
  const formRef = ref();

  // 查询
  const findList = async () => {
    const data = await getUserList({ ...formState });
    dataSource.value = data || [];
  };

  // 检索
  const reset = () => {
    formState.username = '';
    delete formState.active;
  };
  // 删除
  const delUser = async (id: number) => {
    await deleteUser({ id: id });
    message.success('用户删除成功');
    findList();
  };

  // 角色
  const roleData = ref([]);
  const originRoleData = ref([]);
  const getRoleSelectList = async () => {
    const data = await getRoleList();
    originRoleData.value = data || [];
    roleData.value = data.map((item) => ({
      label: `${item.name} - ${item.remark}`,
      value: item.id,
    }));
  };

  // 弹窗
  //#region
  const visible = ref(false);
  const addUser = () => {
    drawTit.value = '新建用户';
    console.log(formObj.value);

    visible.value = true;
  };
  const editUser = async (id) => {
    const data = await getUserDetail({ id });
    data.role = JSON.parse(data.role);
    if (data.role.length > 0) {
      data.role = data.role.map(
        (item) => originRoleData.value.find((role) => role.name === item).id,
      );
    }
    formObj.value = {
      ...data,
      avatar: [{ url: data.avatar }],
    };
    drawTit.value = '编辑用户';
    visible.value = true;
  };
  const changeCover = (files) => {
    if (files[0].status === 'done') {
      formObj.value.avatar = files;
      formObj.value.avatar[0].url = files[0].url;
    }
  };
  const handlerClose = () => {
    formObj.value = {};
    visible.value = false;
  };
  const resetPwd = async (id) => {
    await resetUserPwd({ id: id });
    message.success('重置密码成功');
  };
  const handleChange = (value) => {
    formObj.value.role = value;
  };
  const btnOk = async () => {
    await formRef.value.validate();
    console.log(formObj.value);
    if (formObj.value.role.length > 0) {
      formObj.value.role = JSON.stringify(
        formObj.value.role.map(
          (item) => originRoleData.value.find((role) => role.id === item).name,
        ),
      );
    }
    const submitData = {
      ...formObj.value,
      active: formObj.value.active ? formObj.value.active : '1',
      role: formObj.value.role ? formObj.value.role : '[]',
      password: md5('123456'),
      avatar: formObj.value.avatar?.[0]?.url || '', // 后端需要的字段可能是字符串
    };
    if (formObj.value.id) {
      // 编辑
      await updateUser(submitData);
      message.success('更新用户成功');
    } else {
      // 新增
      await createUser(submitData);
      message.success('创建用户成功');
    }
    handlerClose();
    findList();
  };
  //#endregion
</script>

<style scoped lang="less">
  .wrapper {
    padding: 20px;

    .search {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #fff;
    }

    .tableWrapeer {
      padding: 20px;
      background-color: #fff;

      .btnUnion {
        margin-bottom: 10px;
      }
    }
  }

  .custom-class {
    .formFlex {
      display: flex !important;
    }

    .formFlex > *:last-child {
      margin-left: 20px;
    }
  }
</style>
